package com.xy.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class GloallyUniqueId implements Watcher {
    //计数器对象
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    //连接对象
    private static ZooKeeper zooKeeper;
    private static String zkConnUrl = "127.0.0.1:2181";
    private static String uniquePath = "/node";

    public GloallyUniqueId() throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(zkConnUrl,5000, this);
        countDownLatch.await();
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.None) {
            switch (watchedEvent.getState()) {
                case SyncConnected:
                    System.out.println("连接成功");
                    countDownLatch.countDown();
                    break;
                case Disconnected:
                    System.out.println("断开连接");
                    break;
                case Expired:
                    System.out.println("会话过期");
                    break;
                case AuthFailed:
                    System.out.println("授权失败");
                    break;
            }
        }
    }

    public String getUniqueId() throws KeeperException, InterruptedException {
        String path = zooKeeper.create(uniquePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        return path.substring(5);
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        GloallyUniqueId gloallyUniqueId = new GloallyUniqueId();
        for (int i = 0; i < 6; i++) {
            String id = gloallyUniqueId.getUniqueId();
            System.out.println(id);
        }
        zooKeeper.close();
    }

}
